import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import storage from "@/utils/localStorageUtils.js";
import { deepCopy } from "@/utils/objectUtils.js"
import { getRouters, getToken } from "@/utils/auth.js"
import { Message } from 'element-ui'

Vue.use(VueRouter)

// 解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace

// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  return originalPush.call(this, location).catch((err) => err)
}

// replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  return originalReplace.call(this, location).catch((err) => err)
}

const routes = [
  {
    path: '/login',
    name: '登录页',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/404',
    name: '资源访问路径找不到',
    component: () => import('@/views/error/NotFound.vue')
  },
  {
    path: '/',
    component: () => import('@/components/layout/Main.vue'),
    // 重定向
    redirect: '/home',
    name: 'root',
    // 子路由
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/index.vue')
      },
      {
        path: '/personalCenter',
        name: 'personalCenter',
        meta: { crumbs: ["个人中心"] },
        component: () => import('@/views/system/user/profile/index.vue')
      }
    ]
  },
]

// 创建路由的方法
let createRouter = () => new VueRouter({
  // hash history后端支持可开,需配置nginx， 次模式下不会再返回404界面
  mode: 'history',
  routes,
  // 在切换时定位路由滚动条的位置
  scrollBehavior: () => ({ y: 0 })
});

// 清空路由的方法
export function resetRouter() {
  router.matcher = createRouter().matcher
}

const router = createRouter()

// 路由白名单，不需要拦截的
const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {

  console.log("-------------from->", from.path, "-------------to >", to.path, "-------------");

  if (getToken()) {
    // 有 token 不允许重复登录
    if (to.path === '/login') {
      next({ path: '/' })
    } else if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      // 判断一下，用户是否已经拉取完毕用户信息
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(() => {
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 清除路由
            resetRouter()

            // 根据roles权限生成可访问的路由表
            router.addRoute(accessRoutes) // 动态添加可访问路由表

            if (from.path == "/login") {
              next("/");
            } else {
              next({ ...to, replace: true }) // back方法 确保addRoutes已完成
            }
          })
        }).catch(err => {
          store.dispatch('Logout').then(() => {
            Message.error(err)
            next({ path: '/' })
          })
        })

        // 获取系统配置
        store.dispatch("GetConfig");
      } else {
        next();
      }
    }
  } else {
    // 没有 token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next("/login");
    }
  }
})

export default router
